import csv
import math
import sys
import os

TERM = 2
KEYS = ['deer','elk','moose','horse']

class DataPoint:
    def __init__(self, *args):
        if len(args) != 26:
            raise "Expected 26 args, got %d" % len(args)

        self.location = args[0]
        self.transect_id = args[1]
        
        self.coord = (int(args[2]),int(args[3]))

        self.data = {}
        self.data['deer'] = float(args[22])
        self.data['elk'] = float(args[23])
        self.data['moose'] = float(args[24])
        self.data['horse'] = float(args[25])

    def distance(self,other):
        """sqrt(  (eastingA - eastingB)^2 + (northingA - northingB)^2  )"""

        (easta,northa) = self.coord
        (eastb,northb) = other.coord

        eastab = easta - eastb
        northab = northa - northb

        return math.sqrt( (eastab*eastab) + (northab*northab) )



def interpolateForPoint(point, alldata):

    rtn = {}

    for key in KEYS:
        top = 0.0
        bottom = 0.0
        for p in alldata:
            if p is point:
                continue

            dist = p.distance(point)
            distpow = (math.pow(dist,TERM))

            top = top + (p.data[key] / distpow)
            bottom = bottom + (1.0 / distpow)

        rtn[key] = top / bottom

    return rtn



def processFile(fname):
    print 'Processing "%s"' % fname
    
    # open file, read all lines and trim off the first one (column headers)
    try:
        lines = open(fname).readlines()[1:]
    except IOError:
        print 'Error opening/reading "%s"...' % fname
        return

    # parse it as a CSV file
    input = csv.reader(lines)

    # "data" is any data with actual coordinates
    data = []

    try:
        last = None
        while True:
            foo = input.next()
            pt = DataPoint(*foo)
            data.append(pt)
    except StopIteration:
        pass

    output = open(os.path.splitext(fname)[0] + '-interpolated.csv','w')
    keys = ', '.join(KEYS)
    output.write('Point Number, ' + keys + '\n')

    i = 0;
    for x in data:
        i = i + 1
        d = interpolateForPoint(x, data)
        print i,d
        formatted = ''
        for k in KEYS:
            formatted = formatted + '%f, ' % d[k]
        formatted = formatted[:-2]      # take off trailing ", "
        output.write('%d, '%i + formatted + '\n')

    output.close()

for file in sys.argv[1:]:
    processFile(file)
